package com.elric.mall.service.impl;

import com.elric.mall.mapper.UmsAdminMapper;
import com.elric.mall.security.service.RedisService;
import com.elric.mall.model.UmsAdmin;
import com.elric.mall.model.UmsAdminExample;
import com.elric.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.security.Principal;
import java.util.List;

/**
 * 实现功能：
 *
 * @author 作者[Yuxuan.he]
 * @version 1.0.00  2021-10-18 10:31
 */
@Service
public class UserServiceImpl implements UserService {

    @Value("${redis.database}")
    private String REDIS_DATABASE;

    @Value("${redis.key.admin}")
    private String REDIS_KEY_ADMIN;

    @Value("${redis.expire.common}")
    private Long REDIS_EXPIRE;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UmsAdminMapper adminMapper;

    @Override
    public UmsAdmin getAdminByPrincipal(Principal principal) {
        String username = principal.getName();
        String key = REDIS_DATABASE + ":" + REDIS_KEY_ADMIN + ":" + username;
        UmsAdmin admin = (UmsAdmin) redisService.get(key);
        if(admin!=null) return  admin;
        UmsAdminExample example = new UmsAdminExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsAdmin> adminList = adminMapper.selectByExample(example);
        if (adminList != null && adminList.size() > 0) {
            admin = adminList.get(0);
            redisService.set(key, admin, REDIS_EXPIRE);
            return admin;
        }
        return null;
    }
}
